package com.youmingxing.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.tencent.upload.task.ITask;
import com.tencent.upload.task.IUploadTaskListener;
import com.tencent.upload.task.data.FileInfo;
import com.youmingxing.R;
import com.youmingxing.activity.selfInfo.TopicActivity;
import com.youmingxing.network.AllStarApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.network.TXYUploadManager;
import com.youmingxing.utils.DisplayUtil;
import com.youmingxing.utils.FileUtils;
import com.youmingxing.utils.LogUtil;
import com.youmingxing.utils.Util;
<<<<<<< Updated upstream
import com.youmingxing.view.TextLengthWatcher;
import com.youmingxing.view.clipheadphoto.ClipSquareImageView;
import com.youmingxing.view.clipheadphoto.clip1.ClipImageLayout;
import com.youmingxing.view.clipheadphoto.util.ImageTools;
=======
import com.youmingxing.view.TextLengthAndContentWatcher;
>>>>>>> Stashed changes

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;


/**
 * @author evilyin(ChenZhixi)
 * @since 2015-9-7
 */

public class UploadActivity extends BaseActivity implements IUploadTaskListener {


    EditText editText;
    GridView photoGrid;
    private FrameLayout frameLayout;
    String filePath;
    ArrayList<String> photoArray = new ArrayList<>();
    int type;
    UploadAdapter uploadAdapter;

    //上传成功的视频url
    String videoUrl = "";
    String thumbnailUrl = "";
    String smallImgPath = "";
    Bitmap thumbnail;
    private ClipImageLayout mClipImageLayout;
    private boolean isUploadSmallImg = true;
    private String smallImgUrl = "";
    private boolean isSubmit = false;
    private ClipSquareImageView clipSquareImageView;
    private boolean isWidthBig = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseSetContentView(R.layout.activity_upload1);
        setTopbarName("上传作品");

        Bundle bundle = getIntent().getExtras();
        filePath = bundle.getString("path");
        type = bundle.getInt("type");
        photoArray = bundle.getStringArrayList("photo_array");

        editText = (EditText) findViewById(R.id.upload_edit_text);
        photoGrid = (GridView) findViewById(R.id.photo_array_grid_view);
        frameLayout = (FrameLayout) findViewById(R.id.framlayout);

        if (type == 0) {
            frameLayout.setVisibility(View.GONE);
            photoGrid.setVisibility(View.VISIBLE);
            uploadAdapter = new UploadAdapter();
            photoGrid.setAdapter(uploadAdapter);
        } else {
            photoGrid.setVisibility(View.GONE);
            frameLayout.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(photoArray.get(0)) || !(new File(photoArray.get(0)).exists())) {
                Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();
                return;
            }
            mClipImageLayout = (ClipImageLayout) findViewById(R.id.id_clipImageLayout);
            String widthAndHight = ImageTools.getHight(photoArray.get(0));
            int width = Integer.valueOf(widthAndHight.split(",")[0]);
            int hight = Integer.valueOf(widthAndHight.split(",")[1]);
            LogUtil.i("--------width--", "width: " + width + " "
                    + (double) width / hight + " " + hight);
            Bitmap bitmap;
            if ((double) (width * 9 / hight) < 16) { //  竖直方向移动 16/9 = 1.7777777777778
                isWidthBig = false;
                if (hight >= 3600) {
                    LogUtil.i("--------width--", "  11");
                    bitmap = ImageTools.convertToBitmap(photoArray.get(0), 1200, 800);
                    bitmap = ImageTools.upImageSize(bitmap,
                            DisplayUtil.getScreenWidth(),
                            (DisplayUtil.getScreenWidth() * hight / width));
                } else {
                    if (width < hight) {
                        bitmap = ImageTools.convertToBitmap(photoArray.get(0), width, hight);
                        bitmap = ImageTools.upImageSize(bitmap,
                                DisplayUtil.getScreenWidth(),
                                (int) (DisplayUtil.getScreenWidth() * ((double) width / hight)));
                    } else {
                        bitmap = ImageTools.convertToBitmap(photoArray.get(0), width, hight);
                        bitmap = ImageTools.upImageSize(bitmap,
                                (DisplayUtil.getScreenWidth() ) ,
                                DisplayUtil.getScreenWidth() * hight/width);
                        if ((float) width / hight > 1.7 && (float) width / hight < 1.8) {
                            mClipImageLayout.setmZoomImageView(0);
                        } else if ((float) width / hight > 1.6 && (float) width / hight <= 1.7) {
                            mClipImageLayout.setmZoomImageView(0.1f);
                        } else if ((float) width / hight > 1.45 && (float) width / hight <= 1.6) {
                            mClipImageLayout.setmZoomImageView(0.2f);
                        } else if ((float) width / hight <= 1.0) {
                            mClipImageLayout.setmZoomImageView(0f);
                        } else {
                            LogUtil.i("--------width--", "  12  - " + width + " " + hight);
                            mClipImageLayout.setmZoomImageView(1.8f - (float) width / hight);
                        }
                    }
                    mClipImageLayout.setsetHight(bitmap.getHeight());
                    LogUtil.i("--------width--", "  11   hh " + bitmap.getHeight());

                }
            } else if ((double)(width * 9 / hight )== 16) { //  竖直方向移动
                isWidthBig = false;
                LogUtil.i("--------width--", "  000 ");
                bitmap = ImageTools.convertToBitmap(photoArray.get(0), width, hight);
                bitmap = ImageTools.upImageSize(bitmap,
                        (DisplayUtil.getScreenWidth() * 9 / 16) * width / hight,
                        DisplayUtil.getScreenWidth() * 9 / 16);
                mClipImageLayout.setmZoomImageView(0);
            } else {
                isWidthBig = true;
                LogUtil.i("--------width--", " 22");
                if (width > 3600) {
                    LogUtil.i("--------width--", " 21");
                    bitmap = ImageTools.convertToBitmap1(photoArray.get(0), (DisplayUtil.getScreenWidth() * 9 / 16 + 150) * width / hight,
                            DisplayUtil.getScreenWidth() * 9 / 16 + +60);
                    bitmap = ImageTools.upImageSize(bitmap,
                            (DisplayUtil.getScreenWidth() * 9 / 16) * width / hight,
                            DisplayUtil.getScreenWidth() * 9 / 16);
                } else {

                    bitmap = ImageTools.convertToBitmap(photoArray.get(0), width, hight);
                    bitmap = ImageTools.upImageSize(bitmap,
                            (DisplayUtil.getScreenWidth() * 9 * width / (16 * hight)),
                            DisplayUtil.getScreenWidth() * 9 / 16);
                }
                mClipImageLayout.setmZoomImageView(0);
            }
            if (bitmap == null) {
                Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();
                return;
            }
            mClipImageLayout.setBitmap(bitmap);
            mClipImageLayout.setLayoutParams(new FrameLayout.LayoutParams(
                    DisplayUtil.getScreenWidth(),
                    FrameLayout.LayoutParams.MATCH_PARENT));

        }


        setLeftAndrightTv(true, true, false, R.string.post, null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editText.getText().toString().isEmpty()) {
                    showToast("您还没有输入内容哦");
                } else {
                    if (!isSubmit) {
                        showDialog("正在上传");
                        startUpload();
                        isSubmit = true;
                    }
                }
            }
        }, null);
        editText.addTextChangedListener(new TextLengthAndContentWatcher(
                UploadActivity.this, 60, editText));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TextLengthAndContentWatcher.REQUESTCODE_TOPIC &&
                resultCode == TopicActivity.RESULTCODE_TOPIC) {
            editText.setText("");
            if (data != null) {
                editText.setText(data.getStringExtra("topic_title"));
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void startUpload() {

        switch (type) {
            case 0://video:
                TXYUploadManager.uploadVideo(filePath, this);
                break;
            case 1://photo:
                Bitmap bitmap = mClipImageLayout.clip(isWidthBig);
                smallImgPath = Environment.getExternalStorageDirectory() + "/ClipHeadPhoto/cache/" + System.currentTimeMillis() + ".png";
                ImageTools.savePhotoToSDCard(bitmap, smallImgPath);
                TXYUploadManager.uploadPhoto(smallImgPath, this);
                break;
        }
    }

    BaseJsonHandler uploadHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
//            showToast("上传成功");
            setResult(RESULT_OK);
            isSubmit = false;
            FileUtils.fileDeleted(Environment.getExternalStorageDirectory() + "/ClipHeadPhoto/cache/");
            Intent intent = new Intent(UploadActivity.this, WorksCommitSucceedActivity.class);
            intent.putExtra("entrance", 3);
            intent.putExtra("content", editText.getText().toString());
            try {
                intent.putExtra("id", response.getJSONObject("data").optInt("id", 0));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            startActivity(intent);
            finish();
        }
    };

    @Override
    public void onUploadSucceed(FileInfo fileInfo) {
        Log.i("upload", fileInfo.url);
        String title = editText.getText().toString();

        switch (type) {
            case 0:
                //视频
                if (videoUrl.isEmpty() && thumbnailUrl.isEmpty()) {
                    //视频上传成功
                    videoUrl = fileInfo.url;
                    TXYUploadManager.uploadPhoto(Util.Bitmap2Bytes(thumbnail), this);
                } else if (!videoUrl.isEmpty() && thumbnailUrl.isEmpty()) {
                    //视频缩略图上传成功
                    thumbnailUrl = fileInfo.url;
                    AllStarApi.postNewContent(2, title, videoUrl, thumbnailUrl, uploadHandler);
                    videoUrl = "";
                    thumbnailUrl = "";
                }
                break;
            case 1:
                if (isUploadSmallImg) {
                    smallImgUrl = fileInfo.url;
                    TXYUploadManager.uploadPhoto(photoArray.get(0), this);
                    isUploadSmallImg = false;
                } else {

                    AllStarApi.postNewContent(1, title, fileInfo.url, smallImgUrl, uploadHandler);
                }
                break;
        }

    }

    @Override
    public void onUploadFailed(int i, String s) {
        showToast("上传失败");
        hideDialog();
    }

    @Override
    public void onUploadProgress(long l, long l1) {

    }

    @Override
    public void onUploadStateChange(ITask.TaskState taskState) {

    }

    private class UploadAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            switch (type) {
                case 0://video:
                    return 1;
                case 1://photo:
                    return photoArray == null ? 0 : photoArray.size();
                default:
                    return 0;
            }
        }

        @Override
        public Object getItem(int position) {
            switch (type) {
                case 0:
                    return filePath;
                case 1:
                    return photoArray.get(position);
                default:
                    return null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView = new ImageView(UploadActivity.this);
            imageView.setLayoutParams(new AbsListView.LayoutParams(200, 200));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            switch (type) {
                case 0:
                    //视频
                    thumbnail = ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Images
                            .Thumbnails.MINI_KIND);
                    imageView.setImageBitmap(thumbnail);
                    break;
                case 1:
                    Glide.with(UploadActivity.this).load(photoArray.get(position))
                            .crossFade().into
                            (imageView);
                    break;
            }
            return imageView;
        }
    }
}
